<style lang="scss" scoped>
.examination-paper-info {
  padding: 20px;
  display: flex;
  flex-direction: column;
  &__header-action {
    display: flex;
    margin: 0 0 20px 0;
  }
  .search-box{
    margin: 20px 0;
  }
&-warp {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  .col-warp {
  padding-top: 15px;
  .search-warp {
  display: flex;
  align-items: center;
  .title {
    color: #8e8e8e;
    margin-right: 10px;
  }
  .interval {
    display: flex;
    align-items: center;
    .center-text {
      margin: 0 10px;
    }
  }
}
}
}

&-content {
  .name {
    display: flex;
    margin-bottom: 20px;
    .lable {
      width: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
.paper-import {
    &__upload {
      padding: 15px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

  }
}
.paper-import__tips {
  &--action {
    color: #1890ff;
    cursor: pointer;
  }
}
:deep(.paper-import) {
  .el-dialog__body {
    padding: 0;
  }
}

</style>
<script>
import Pagination from '@/components/Pagination'
import ImportOperation from '@/views/examination/components/ImportOperation.vue'
import {
  getPaper,
  setUpPaper,
  modifyPaper,
  deletePaper,
  importTestPaper,
  analysisTest,
  analysisTestImport,
} from '@/api/examination'
export default {
  components: {
    Pagination,
    ImportOperation
  },
  data() {
    return {
      list: [],
      topicTabel:[],
      title:'',
      percentage:'',
      state: 'normal',
      type: 'add',
      addDialogVisible: false,
      from: {
        title: '',
        pass_percentage: null,
        // points: '',
        // pass: '',
        open: true
      },
      page: {
        paginate: 10,
        page: 1,
        total: 1,
        // topic: '',
        open: null,
        title: '',
        points: [],
        pass: []
      },
      loading: false,
      selectOptions: [
        { label: '启用', value: 1 },
        { label: '未启用', value: 0 }
      ],
      paperRules: {
        title: [
          { required: true, message: '请输入试卷名称', trigger: ['blur', 'change'] }
        ],
        pass_percentage: [
          { required: true, message: '请选择及格百分比', trigger: ['blur', 'change'] }
        ]
      },
      sampleFileDownLoadAddr: 'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/test_1687929722_VvAtwFHHfd.xlsx'
    }
  },
  created() {
    this.getdata()
  },
  methods: {
    handleSearch() {
      if (
        (this.page.points.length >= 1 && this.page.points.length < 2) ||
        (this.page.pass.length >= 1 && this.page.pass.length < 2)
      ) {
        return this.$message.error('请将区间信息填写完整')
      }
      this.page.page = 1
      this.getdata()
    },
    resetSearchInfo() {
      this.page = this.$options.data().page
      this.getdata()
    },
    paramsFormat(params) {
      const a = {
        paginate: params.paginate,
        page: params.page,
        open: params.open,
        title: params.title,
        points: params.points.length > 0 ? JSON.stringify(params.points) : null,
        pass: params.pass.length > 0 ? JSON.stringify(params.pass) : null
      }
      Object.keys(a).forEach(item => {
        if (item === null) delete a[item]
      })
      return a
    },
    pagination(e) {
      this.page.page = e.page
      this.page.paginate = e.limit
      this.getdata()
    },
    getdata() {
      this.loading = true
      const { paginate, page, open, title, points, pass } = this.page
      const params = this.paramsFormat({ paginate, page, open, title, points, pass })
      console.log('params ------>', params)
      getPaper(params)
        .then((res) => {
          console.log(res, '123123123123')
          this.list = res.data
          this.page.total = res.meta.total
        })
        .catch((err) => {})
      this.loading = false
    },
    // 新增试卷
    newPosition() {
      this.type = 'add'
      this.from = {
        title: '',
        pass_percentage: 0,
        open: true
      }
      this.addDialogVisible = true
      this.$nextTick(() => {
        this.$refs.elFormRef.resetFields()
      })
    },
    // 修改试卷
    handleEdit(index, row) {
      console.log('row ------>', row)
      this.type = 'edit'
      this.from.title = row.title
      this.from.pass_percentage = row.pass_percentage
      this.from.open = row.open === 1
      this.addDialogVisible = true
      this.from.id = row.id
    },
    // 恢复试卷和删除试卷
    handleDelete(index, row) {
      this.$confirm('是否删除试卷', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deletePaper({ id: row.id })
            .then((res) => {
              this.$message({
                type: 'success',
                message: '删除试卷成功'
              })
              this.getdata()
            })
            .catch((err) => {})
        })
        .catch((err) => {})
    },
    // 关闭的回调
    closeAgree() {},
    // 取消
    cancel() {
      this.from.title = ''
      this.from.pass_percentage = null
      // this.from.points = ''
      // this.from.pass = ''
      this.from.open = false
      this.addDialogVisible = false
    },
    // 查看详情
    handleDetails(index, data) {
      console.log(index, data)
      this.$router.push({
        path: `/examination/details/${data.id}`,
        query: { tag_title: data.title + '-查看' }
      })
    },
    // 确定
    append() {
      if (!this.from.title) {
        this.$message.error('请输入试卷名称')
      } else if (this.from.pass_percentage == 0) {
        this.$message.error('请输入及格百分比')
      } else if (this.type == 'add') {
        setUpPaper({ ...this.from, open: this.from.open ? 1 : 0 })
          .then((res) => {
            this.addDialogVisible = false
            this.$message({
              type: 'success',
              message: '新建试卷成功'
            })
            this.getdata()
          })
          .catch((err) => {})
      } else {
        const data = {
          title: this.from.title,
          pass_percentage: this.from.pass_percentage,
          // points: this.from.points,
          // pass: this.from.pass,
          open: this.from.open ? 1 : 0,
          id: this.from.id
        }
        modifyPaper(data)
          .then((res) => {
            this.addDialogVisible = false
            this.$message({
              type: 'success',
              message: '修改试卷信息成功'
            })
            this.getdata()
          })
          .catch((err) => {})
      }
    },

    handleAddSubject(row) {
      console.log('row ------>', row)
      this.$router.push({
        path: '/examination/show/',
        query: { paper_id: row.id, tag_title: '加入试卷' }
      })
    },

     async onUploadEvent(e) {
      try {
        if (!(e.file instanceof File)) {
          return
        }

        const formData = new FormData()
        formData.append('file', e.file)
        const result = await analysisTest(formData)
        if (result.code !== 200 || !Array.isArray(result.data)) {
          throw new Error(result.message ?? '解析Excel文件解析失败')
        }
        const {title,percentage}=this.getPaperMesg(result.data);
        this.title=title
        this.percentage=percentage.split(":")[1].replace("%", "");
        console.log(this.percentage,'percentage');
        const newData = result.data.slice(2);
        const deletedItem = newData.pop();
        this.topicTabel=newData.map(item=>{
          return {
            topic:item[0],
            option:item[1],
            answer:item[2],
            type:{
              label:item[3],
              value:this.getValue(item[3])
            }
          }
        })
        this.$refs.importOperationRef.isShowUpload=false
        console.log(this.topicTabel,' topicTabel');
      } catch (error) {
        console.log(error)
        const errMsg = error?.response?.data?.message ??
            '解析Excel文件解析失败'
        this.$message.error(errMsg)
      }
      // this.importTestPaperApi(e)
    },
    async handleUploadSumbits(data){
      try {
        const res=await analysisTestImport(data)
        console.log(res,'res');
        this.refresh()
        this.$refs.importOperationRef.show=false
        this.$message.success('导入成功')
      } catch (error) {
        console.log(error,'err');
        this.$message.error(error.response?.data?.message || '导入失败')
        // this.$refs.importOperationRef.clearUploadedFiles()
      }
    },
    getValue(obj){
      if (obj==='单选') {
        return 1
      } else if (obj==='多选') {
        return 2
      } else if (obj==='判断'){
        return 3
      }
    },
    getPaperMesg(arr){
      let obj={}
      if (Array.isArray(arr) && arr.length>0) {
        arr.map((item,index)=>{
          switch (index) {
            case 0:
              return obj.title=item[0]
            case arr.length-1:
              return  obj.percentage=item[0]
            default:
              return
          }
        })
        return obj
      }
    },

    async importTestPaperApi(data) {
      try {
        const res = await importTestPaper(data)
        if (res.code === 200) {
          this.$message.success('试卷导入成功')
          this.refresh()
        }
      } catch (error) {
        this.$message.error(error.response.data.message || '试卷导入失败')
        this.clearUploadedFiles()
      }
    },

    clearUploadedFiles() {
      this.$refs.importOperationRef.clearUploadedFiles()
    },

    handleSettingMark() {
      this.$router.push({
        path: '/examination/show'
      })
    },

    handleDownLoadSampleFile() {
      window.open(this.sampleFileDownLoadAddr)
    },

    refresh() {
      this.getdata()
    }
  }
}
</script>
<template>
  <div class="examination-paper-info">
    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="试卷名称">
          <el-input
            v-model="page.title"
            placeholder="根据试卷名称搜索"
            clearable
            class="search-ipt"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button type="danger" @click="resetSearchInfo">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="examination-paper-info__header-action">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="newPosition()"
        >新增试卷</el-button>
        <ImportOperation
          ref="importOperationRef"
          dialog-title="试卷导入"
          :isShowPaper="true"
          :title="title" :percentage="percentage"
          :topicTabel="topicTabel"
          :sample-file-down-load-addr="sampleFileDownLoadAddr"
          @uploadSuccess="onUploadEvent"
          @handleSumbits="handleUploadSumbits"
        >
          导入试卷
          <template #tips>
            <el-alert
              type="warning"
              class="paper-import__tips"
              :closable="false"
            >
              在导入试卷前，请确保您已经设置好了各类题型的分数，
              <span class="paper-import__tips--action" @click="handleSettingMark">
                如若未设置请前往设置
              </span>，如已设置请忽略！
            </el-alert>
          </template>
        </ImportOperation>
      </div>
      <el-table v-loading="loading" :data="list" border stripe>
        <el-table-column label="试卷名称" prop="title" align="center" />
        <el-table-column label="及格分" prop="pass" align="center">
          <template v-slot="{ row }"><span> {{ row.pass ?? 0 }} </span></template>
        </el-table-column>
        <el-table-column label="满分" prop="points" align="center" />

        <el-table-column label="是否启用" prop="open" align="center">
          <template v-slot="{ row }">
            <span>{{ row.open === 1 ? '启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" align="center" />
        <el-table-column label="最后修改时间" prop="updated_at" align="center" />
        <el-table-column width="200px" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleAddSubject(scope.row)"
            >添加题目</el-button>
            <el-button
              size="mini"
              type="success"
              style="margin-bottom: 5px;"
              @click="handleDetails(scope.$index, scope.row)"
            >查看详情</el-button>
            <el-button
              size="mini"
              type="warning"
              style="margin: 0;"
              @click="handleEdit(scope.$index, scope.row)"
            >修改试卷</el-button>

            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除试卷</el-button>

          </template>
        </el-table-column>
      </el-table>
      <div>
        <Pagination style="margin-top: 0; padding-bottom: 0;" :total="page.total" :limit="page.paginate" @pagination="pagination" />
      </div>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      :title="type == 'add' ? '新增试卷' : '修改试卷'"
      :visible.sync="addDialogVisible"
      width="30%"
      center
      @close="closeAgree"
    >
      <el-form ref="elFormRef" label-position="top" label-width="80px" :model="from" :rules="paperRules">
        <el-form-item label="试卷名称" prop="title">
          <el-input
            v-model="from.title"
            placeholder="请输入试卷名称"
          />
        </el-form-item>

        <el-form-item label="及格百分比" prop="pass_percentage">
          <el-slider v-model="from.pass_percentage" />
        </el-form-item>

        <el-form-item v-if="type === 'edit'" label="是否开启">
          <el-switch
            v-model="from.open"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="append()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
